package user

import (
	"context"

	"github.com/gogf/gf/v2/crypto/gmd5"
	"github.com/gogf/gf/v2/errors/gerror"

	v1 "gitee.com/liangziyisheng/caas-platform-mc/api/user/v1"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/consts"
	"gitee.com/liangziyisheng/caas-platform-mc/internal/service"
	"gitee.com/liangziyisheng/caas-platform-mc/utility/utils"
)

func (c *ControllerV1) Add(ctx context.Context, req *v1.AddReq) (res *v1.AddRes, err error) {
	tenantCode := ctx.Value(consts.TokenClaims.TenantCode).(string)

	in := &v1.AddInput{}
	utils.CopyStruc(*req, in)
	in.Status = consts.UserStatus[1].Value
	in.TenantCode = tenantCode
	// 对密码进行md5加密
	if req.Password != "" {
		req.Password, err = gmd5.Encrypt(req.Password)
		if err != nil {
			return nil, gerror.WrapCode(consts.EncryptFailed, err)
		}
		in.Password = req.Password
	}
	out, err := service.User().Add(ctx, in)
	if err != nil {
		return nil, err
	}
	return &v1.AddRes{
		Id: out.Id,
	}, nil
}
